<template>
  <div class="products-container">
    <div class="header">
      <h3>商品管理</h3>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加商品
      </el-button>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchName"
        placeholder="按商品名称搜索"
        style="width: 200px"
        clearable
        @clear="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-select
        v-model="searchCategory"
        placeholder="按类别筛选"
        style="width: 200px; margin-left: 10px"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="category in categories"
          :key="category"
          :label="category"
          :value="category"
        />
      </el-select>
      <el-input-number
        v-model="minPrice"
        placeholder="最低价格"
        style="width: 150px; margin-left: 10px"
        :min="0"
        :precision="2"
        @change="handleSearch"
      />
      <el-input-number
        v-model="maxPrice"
        placeholder="最高价格"
        style="width: 150px; margin-left: 10px"
        :min="0"
        :precision="2"
        @change="handleSearch"
      />
    </div>

    <el-table :data="products" style="width: 100%" v-loading="loading">
      <el-table-column prop="productId" label="商品ID" width="120" />
      <el-table-column prop="name" label="商品名称" width="180" />
      <el-table-column prop="category" label="类别" width="120" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="{ row }">
          {{ row.price }} 元
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api'

const products = ref([])
const categories = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const searchName = ref('')
const searchCategory = ref('')
const minPrice = ref(null)
const maxPrice = ref(null)

const form = ref({
  productId: '',
  name: '',
  category: '',
  price: 0,
  description: ''
})

const rules = {
  productId: [
    { required: true, message: '请输入商品ID', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    // 移除required验证
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ],
  description: [
    // 移除required验证
  ]
}

const loadData = async () => {
  loading.value = true
  try {
    const response = await api.get('/products')
    products.value = response
    // 提取所有不重复的类别
    categories.value = [...new Set(response.map(p => p.category))]
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
  loading.value = false
}

const handleSearch = async () => {
  loading.value = true
  try {
    const response = await api.get('/products')
    let filteredData = response || []
    
    if (searchName.value) {
      filteredData = filteredData.filter(item => 
        item.name.toLowerCase().includes(searchName.value.toLowerCase())
      )
    }
    if (searchCategory.value) {
      filteredData = filteredData.filter(item => item.category === searchCategory.value)
    }
    if (minPrice.value !== null) {
      filteredData = filteredData.filter(item => item.price >= minPrice.value)
    }
    if (maxPrice.value !== null) {
      filteredData = filteredData.filter(item => item.price <= maxPrice.value)
    }
    
    products.value = filteredData
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
  loading.value = false
}

const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    productId: '',
    name: '',
    category: '',
    price: 0,
    description: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    productId: row.productId,
    name: row.name,
    category: row.category,
    price: row.price,
    description: row.description
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await api.delete(`/products/${row.productId}`)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await api.post('/products', form.value)
          ElMessage.success('添加成功')
        } else {
          await api.put(`/products/${form.value.productId}`, form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.products-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 